package com.rpay.admin.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.rpay.admin.util.SessionUtil;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.util.common.CommonUtils;
import com.rpay.common.util.cyptor.Cryptor;
import com.rpay.common.vo.PcsResult;
import com.rpay.model.admin.RpayAdminUser;
import com.rpay.model.admin.RpayAdminUserRole;
import com.rpay.service.admin.impl.SecUserRoleServiceImpl;
import com.rpay.service.admin.impl.SystemUserServiceImpl;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by Administrator on 2018/1/24 0024.
 */
@RestController
@RequestMapping("/api/admin/user")
@Scope(value = "prototype")
public class AdminUserController {

    @Resource(name = "systemUserServiceImpl")
    private SystemUserServiceImpl userMapperServiceImpl;
    @Resource(name = "userRoleServiceImpl")
    protected SecUserRoleServiceImpl userRoleServiceImpl;


    @Autowired
    protected SystemUserServiceImpl systemUserService;
//    @Autowired
//    private SysMetadataServiceImpl sysMetadataServiceImpl;

//    @Autowired
//    private CustomInvocationSecurityMetadataSourceService customInvocationSecurityMetadataSourceService;

    /**
     * 新增用户
     *
     * @param user 用户信息
     * @return 新增结果
     */
    @RequestMapping(value = "/userAdd", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @Transactional
    public PcsResult addUser(@RequestBody RpayAdminUser user) {
        if (CommonUtils.isEmpty(user)
                || CommonUtils.isEmpty(user.getUsername())) {
            return PcsResult.build(PcsResultCode.PARAM_INVALID);
        }
        //查询账号是否存在
        String username = user.getUsername();
        RpayAdminUser model = userMapperServiceImpl.findByName(username.trim());
        if (!CommonUtils.isEmpty(model)) {
            return PcsResult.build(PcsResultCode.BUSINESS_USER_EXISTED);
        }


        //保存用户
        String password = user.getPassword();
        user.setPassword(Cryptor.crypto(password));
        user.setParentOrgId(SessionUtil.getOrgId());
//        user.setCreatedTime(new Date());
        userMapperServiceImpl.saveModel(user);


        //保存用户角色关系
        RpayAdminUser savedModel = userMapperServiceImpl.findByName(user.getUsername());

        RpayAdminUserRole secUserRole = new RpayAdminUserRole();
        secUserRole.setUserId(savedModel.getId());
        secUserRole.setRoleId(user.getRoleId());
        userRoleServiceImpl.saveModel(secUserRole);
        //重新加载角色权限


        return PcsResult.build(PcsResultCode.SUCCESS);
    }

    /**
     * 修改用户
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/userEdit", method = RequestMethod.PUT)
    @Transactional
    public PcsResult editUser(@RequestBody RpayAdminUser user) {
        if (CommonUtils.isEmpty(user)
                || CommonUtils.isEmpty(user.getId())) {
            return PcsResult.build(PcsResultCode.PARAM_INVALID);
        }
        Long userId = user.getId();


        //删除旧的角色关系
        Long roleId = user.getRoleId();
        if (!CommonUtils.isEmpty(roleId)) {
            Map map = new HashMap();
            map.put("userId", userId);
            userRoleServiceImpl.deleteBySql("deleteUserRole", map);
            //保存用户角色关系
            RpayAdminUserRole secUserRole = new RpayAdminUserRole();
            secUserRole.setUserId(userId);
            secUserRole.setRoleId(roleId);
            userRoleServiceImpl.saveModel(secUserRole);

        }


        //修改用户信息
        userMapperServiceImpl.modModelByPrimaryKey(user);

        return PcsResult.build(PcsResultCode.SUCCESS);
    }




    /**
     * 查询当前用户下级用户（包括子级、子级的子级等）类型列表
     *
     * @return 查询结果
     */



    private List<Map> userTypes = new ArrayList<>();


    /**
     */
    @RequestMapping(value = "/userList", method = RequestMethod.GET)
    public PcsResult getuserList(@RequestParam(name = "page", defaultValue = "1") Integer page,
                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, String name, String startDate, String endDate) {
        Map param = new HashMap();
        if (!CommonUtils.isEmpty(name)) {
            param.put("realname", "%" + name + "%");
        }
        if (!CommonUtils.isEmpty(startDate)) {
            param.put("startDate", startDate);
        }
        if (!CommonUtils.isEmpty(endDate)) {
            param.put("endDate", endDate);
        }

        List<Map> resultList = userMapperServiceImpl.getUserList(param, new RowBounds((page - 1) * pageSize, pageSize));
        int totalRow = userMapperServiceImpl.getUserCount(param);
        Map result = new HashMap();
        result.put("page", page);
        result.put("pageSize", pageSize);
        result.put("totalRow", totalRow);
        result.put("list", resultList);
        return PcsResult.build(result);
    }

    /**
     * 重置用户密码
     *
     * @param user 用户
     * @return 重置结果
     */
    @RequestMapping(value = "/resetpwd", method = RequestMethod.PUT)
    public PcsResult resetPwd(@RequestBody RpayAdminUser user) {
        if (CommonUtils.isEmpty(user)
                || CommonUtils.isEmpty(user.getId())) {

            return PcsResult.build(PcsResultCode.PARAM_INVALID);
        }
        RpayAdminUser sysUser = (RpayAdminUser) userMapperServiceImpl.getModelById(user.getId());
        if (!CommonUtils.isEmpty(sysUser)) {
            String password = "q123456";
            sysUser.setPassword(Cryptor.crypto(Cryptor.crypto(password)));
            userMapperServiceImpl.modModelByPrimaryKey(sysUser);
            return PcsResult.build(PcsResultCode.SUCCESS.getCode(), "密码已重置为【" + password + "】");
        } else {
            return PcsResult.build(PcsResultCode.USER_UPD_PWD_ERROR);
        }
    }


    /**
     * 冻结或删除用户
     *
     * @return
     */
    @RequestMapping(value = "/userFreeze", method = RequestMethod.PUT)
    public PcsResult userFreeze(@RequestBody Map user) {
        Short freezeType = Short.parseShort(user.get("status").toString());
        Long userId = Long.parseLong(user.get("userId").toString());
        RpayAdminUser tempUser = new RpayAdminUser();
        tempUser.setId(userId);
        tempUser = userMapperServiceImpl.findByUsernoPasswd(tempUser);
        RpayAdminUser currentUser = SessionUtil.getCurrentUser();
        //冻结本级
        if (userId.equals(currentUser.getId())) {
            return PcsResult.build(PcsResultCode.USER_FREEZE_NOT_YOURSELF);
//            return CommonUtils.buildFailMessage("不允许冻结自己");
        }

        tempUser.setStatus((short) freezeType);
        userMapperServiceImpl.modModelByPrimaryKey(tempUser);

        return PcsResult.build(PcsResultCode.SUCCESS);
    }


    /**
     * 修改密码
     *
     * @param object 原密码
     * @return 修改结果
     */
    @RequestMapping(value = "/changePWd", method = RequestMethod.PUT)
    public PcsResult chPwd(@RequestBody JSONObject object) {
        String rawPassword = object.getString("rawPassword");
        String newPassword = object.getString("newPassword");
        String confirmPassword = object.getString("confirmPassword");
        if (CommonUtils.isEmpty(rawPassword)
                || CommonUtils.isEmpty(newPassword)
                || CommonUtils.isEmpty(confirmPassword)) {
            return new PcsResult(PcsResultCode.USER_PASSWORD_NULL);
        }
        RpayAdminUser user = new RpayAdminUser();
        user.setId(SessionUtil.getUserId());
        //校验是否能修改该用户的密码

        RpayAdminUser sysUser = userMapperServiceImpl.findByUsernoPasswd(user);
        if (!Cryptor.crypto(rawPassword).equals(sysUser.getPassword())) {
            return new PcsResult(PcsResultCode.USER_PASSWORD_MATCH);
        }
        if (!newPassword.equals(confirmPassword)) {
            return new PcsResult(PcsResultCode.USER_PASSWORD_NOT_CONFIRM);
        }
        if (!CommonUtils.isEmpty(sysUser)) {
            sysUser.setPassword(Cryptor.crypto(newPassword));
            userMapperServiceImpl.modModelByPrimaryKey(sysUser);
            return new PcsResult(PcsResultCode.SUCCESS);
        } else {
            return new PcsResult(PcsResultCode.USER_UPD_PWD_ERROR);
        }
    }


}
